package it.bambo.common.jpa.model.builder;

import it.bambo.common.jpa.model.Address;
import it.bambo.common.jpa.model.User;

import java.lang.reflect.Field;
import java.util.*;

/**
 * User: <a href="mailto:andreas@bambo.it">Andreas Baumgartner, andreas@bambo.it</a>
 * Date: 12.10.2010
 * Time: 11:44:43
 */
public class UserBuilder {
    private Map<String, Object> values = new HashMap<String, Object>();

    public UserBuilder withId(String id) {
        values.put("id", id);
        return this;
    }

    public UserBuilder withUsername(String username) {
        values.put("username", username);
        return this;
    }

    public UserBuilder withAddresses(Set<Address> addresses) {
        values.put("addresses", addresses);
        return this;
    }

    public UserBuilder withAddresses(Address... addresses) {
        values.put("addresses", new HashSet<Address>(Arrays.asList(addresses)));
        return this;
    }

    public User build() {
        User user = new User();
        for (Map.Entry<String, Object> entry : values.entrySet()) {
            try {
                Field field = user.getClass().getDeclaredField(entry.getKey());
                field.setAccessible(true);
                field.set(user, entry.getValue());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return user;
    }
}
